/*
 * @页面名称:窗体模型字段规则解读类文件
 * @描述:
 * @作者: 研发中心
 * @Date: 2023-07-19 08:57:47
 */
import { removeBlock } from "./until";
import { useDynamicStore } from "@/stores/modules/dynamic";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useCatalogStore } from "@/stores/modules/catalog";
import { useFondsStore } from "@/stores/modules/fonds";
import dtime from "moment";
import ACrypto from "@/utils/crypto";
import vueAxios from "@/api/index";

class Ruler {
  // 当前弹框数据
  modalFormData: any;
  // 字段规则集合
  ruleList: any[];
  //表名
  tableName?: string;
  dictionryStore: any;
  dynamicStore: any;
  fondsStore: any;
  catalogStore: any;
  constructor({
    modalFormData,
    ruleList,
    tableName,
    isMax = true
  }: {
    modalFormData: any;
    ruleList: any[];
    tableName?: string;
    isMax?: Boolean;
  }) {
    this.modalFormData = modalFormData;
    this.dictionryStore = useDictionryStore();
    this.dynamicStore = useDynamicStore();
    this.fondsStore = useFondsStore();
    this.catalogStore = useCatalogStore();
    this.ruleList = ruleList;
    this.tableName = tableName;
    this.isMax = isMax;
  }
  async fieldRuleInit() {
    let { modalFormData, ruleList } = this;
    const { fatherObj } = this.dynamicStore;
    const currCatalog = this.catalogStore.treeNode.Catalog_Code ? this.catalogStore.treeNode.Catalog_Code : "";
    for (let i = 0; i < ruleList.filter(v => v.FR_RuleType == "init").length; i++) {
      const item = ruleList[i];
      try {
        // 获取具体的字段规则
        let fieldRule = removeBlock(item.FR_Rule.trim());
        if (modalFormData[item.FR_TableField]) {
          // 有值的时候就不触发(比如编辑的时候)
        } else if (fieldRule.startsWith(".")) {
          // 解析以.开头的字符串
          let FieldStr = removeBlock(item.FR_Rule.trim()).slice(1);
          if (this.dynamicStore.childLeftClick) {
            modalFormData[item.FR_TableField] = "";
          } else {
            modalFormData[item.FR_TableField] = fatherObj && fatherObj[FieldStr] ? fatherObj && fatherObj[FieldStr] : "";
          }
        } else if (fieldRule.includes("LSH:")) {
          // 获取流水号
          const Res: any = await vueAxios.post(
            "Dynamic/FunctionGetMaxByCondition",
            { tableName: this.tableName, fieldRule: item.FR_Rule, data: modalFormData },
            { noLoading: true }
          );
          if (Res.Mark) {
            modalFormData[item.FR_TableField] = Res.Value;
          }
        } else if (fieldRule.includes("dateTime:")) {
          const param = fieldRule.split(":");
          const newStr = [] as any[];
          param.forEach((item, index) => {
            if (index > 0) {
              newStr.push(item);
            }
          });
          console.log("````````````init触发时间函数", newStr.join(":"));
          modalFormData[item.FR_TableField] = dtime(new Date()).format(newStr.join(":"));
        } else if (fieldRule.includes("currCatalog.")) {
          console.log("string解析", fieldRule);
          const Code = eval(fieldRule) + "·" + modalFormData.Year + "-" + this.PadLeft(modalFormData.Order);
          // eslint-disable-next-line no-eval
          modalFormData[item.FR_TableField] = Code;
        }
      } catch (error) {
        console.log(error);
      }
    }
  }
  async fieldRuleEvent2() {
    let { modalFormData, ruleList } = this;
    const { fatherObj } = this.dynamicStore;

    for (let i = 0; i < ruleList.filter(v => v.FR_RuleType == "trigger").length; i++) {
      const item = ruleList.filter(v => v.FR_RuleType == "trigger")[i];
      try {
        // 获取具体的字段规则
        let fieldRule = item.FR_Rule.trim();
        if (fieldRule.includes("LSH:") && this.isMax) {
          fieldRule = removeBlock(fieldRule);
          // 判断规则内是否包含更改的字段并且判断是否为修改
          let flag = true;
          if (fieldRule.split(":").length > 2) {
            const filedArr = fieldRule.split(":").splice(2);

            filedArr.forEach((FileName: string) => {
              if (modalFormData[FileName] != this.dynamicStore.oldModalFormData[FileName]) {
                flag = false;
              }
            });
            if (flag) {
              modalFormData[item.FR_TableField] = this.dynamicStore.oldModalFormData[item.FR_TableField];
            } else {
              const Res: any = await vueAxios.post(
                "Dynamic/FunctionGetMaxByCondition",
                { tableName: this.tableName, fieldRule: item.FR_Rule, data: modalFormData },
                { noLoading: true }
              );

              if (Res.Mark) {
                modalFormData[item.FR_TableField] = Res.Value;
              }
            }
          }
        } else if (fieldRule.includes("constant:")) {
          // fieldRule.includes("constant:") && this.type === 1 && !fatherObj
          let regex = /\[([^\]]+)\]/g;
          let regex2 = /\{([^{}]+)\}/g;
          let result: any = fieldRule.match(regex); //获取所有使用[]包含的内容
          let result2: any = fieldRule.match(regex2); //获取所有使用{}包含的内容
          console.log(result, result2);

          //处理[]包起来的，如处理分类，全宗中取常量
          for (let i = 0; i < result.length; i++) {
            const item2 = result[i];
            if (item2.includes("Catalog")) {
              //如果Catalog_ID是NULL为空，就直接返回空
              if (modalFormData.Catalog_ID == null || modalFormData.Catalog_ID == "") {
                fieldRule = fieldRule.replace(item2, "");
              }
              //移除[]
              const newItem = removeBlock(item2, "[]");
              //判断分类的规则是否完整，如：constant:Catalog:Catalog_Code，因为有constant:Catalog这种配制法，这种是默认
              const catalogArr = this.catalogStore.catalogList.filter((v: any) => v.Catalog_ID === modalFormData.Catalog_ID);
              if (newItem.split(":").length > 2) {
                if (catalogArr.length > 0) {
                  const _Catalog = catalogArr[0];
                  if (_Catalog) {
                    const _CatalogVal = _Catalog[newItem.split(":")[2]];
                    fieldRule = fieldRule.replace(item2, _CatalogVal ? _CatalogVal : "");
                  }
                }
              } else {
                //这是配制两个参数的写法，这种是有局限的，固定取Catalog_Code
                if (catalogArr.length > 0) {
                  const _Catalog = catalogArr[0];
                  if (_Catalog) {
                    const _CatalogVal = _Catalog["Catalog_Code"];
                    fieldRule = fieldRule.replace(item2, _CatalogVal ? _CatalogVal : "");
                  }
                } else {
                  //直接替换成空
                  fieldRule = fieldRule.replace(item2, "");
                }
              }
            } else if (item2.includes("Fonds")) {
              //处理全宗相关替换
              //如果Catalog_ID是NULL为空，就直接返回空
              if (modalFormData.Fonds_ID == null || modalFormData.Fonds_ID == "") {
                fieldRule = fieldRule.replace(item2, "");
              }
              //移除[]
              const newItem = removeBlock(item2, "[]");
              //判断分类的规则是否完整，如：constant:fonds:Fonds_ArchivalCode，因为有constant:fonds这种配制法，这种是默认
              const fondsArr = this.fondsStore.fondsData.filter((v: any) => v.Fonds_ID === modalFormData.Fonds_ID);
              if (newItem.split(":").length > 2) {
                if (fondsArr.length > 0) {
                  const _fond = fondsArr[0];
                  if (_fond) {
                    const _fondVal = _fond[newItem.split(":")[2]];
                    fieldRule = fieldRule.replace(item2, _fondVal ? _fondVal : "");
                  }
                }
              } else {
                //这是配制两个参数的写法，这种是有局限的，固定取Fonds_ArchivalCode
                if (fondsArr.length > 0) {
                  const _fond = fondsArr[0];
                  if (_fond) {
                    const _fondVal = _fond["Fonds_ArchivalCode"];
                    fieldRule = fieldRule.replace(item2, _fondVal ? _fondVal : "");
                  }
                } else {
                  //直接替换成空
                  fieldRule = fieldRule.replace(item2, "");
                }
              }
              // fieldRule = fieldRule.replace(item2, this.fondsStore.fondsObj.Fonds_ArchivalCode);
            }
          }

          //处理{}包起来的，如字典替换、补0问题
          for (let i = 0; i < result2.length; i++) {
            const item2 = result2[i];
            const newItem = removeBlock(item2).split(":")[1];
            //处理补0问题
            if (item2.includes("padLeft")) {
              const length = removeBlock(item2).split(":")[2];
              const num = this.PadLeft(modalFormData[newItem], parseInt(length));
              fieldRule = fieldRule.replace(item2, num);
            }

            //处理字典转换
            if (item2.includes("dictionary")) {
              //先去除规则里的{}，然后再用冒号进行分割得到数组
              const dictionaryStrArr = removeBlock(item2).split(":");
              //如果数组长度符合字典规则，如： {dictionary:RetentionPeriod:BGQXdata:DDL_ID:DDL_Name}
              if (this.dictionryStore.dictionaryObj[dictionaryStrArr[2]].length > 0) {
                const dictionaryArr = this.dictionryStore.dictionaryObj[dictionaryStrArr[2]].filter((v: any) => {
                  return v[dictionaryStrArr[3]] === modalFormData[newItem];
                });
                //判断符合规则的字典数据是否有
                if (dictionaryArr.length > 0) {
                  const obj = dictionaryArr[0];
                  fieldRule = fieldRule.replace(item2, obj[dictionaryStrArr[4]] ? obj[dictionaryStrArr[4]] : "");
                } else {
                  fieldRule = fieldRule.replace(item2, "");
                }
              } else {
                fieldRule = fieldRule.replace(item2, "");
              }
            }
            modalFormData[newItem] = modalFormData[newItem] ? modalFormData[newItem] : "";
            fieldRule = fieldRule.replace(item2, modalFormData[newItem]);
          }

          //直接返回原值
          modalFormData[item.FR_TableField] = fieldRule;
        } else if (fieldRule.includes("intercept:")) {
          const newStr = removeBlock(fieldRule);
          fieldRule = modalFormData[newStr.split(":")[1]] ? modalFormData[newStr.split(":")[1]].slice(newStr.split(":")[2]) : "";
          modalFormData[item.FR_TableField] = fieldRule;
        }
      } catch (error) {
        console.log(error);
      }
    }
  }
  /**
   * @名字: 不足百位,前面补零
   * @详情:仅适用于对number的判断
   * @参数:val代表传进来的数字,length代表数据长度,默认为2
   * @返回值:
   */
  PadLeft(val: string, length = 3) {
    return (Array(length).join("0") + val).slice(-length);
  }
  /**
   * @名字: 对字段值加密
   * @详情:仅适用于display类型的字段
   * @参数:
   * @返回值:
   */
  SetEncrypt() {
    const { modalFormData, ruleList } = this;
    for (let i = 0; i < ruleList.length; i++) {
      const item = ruleList[i];
      if (item.FR_RuleType === "display") {
        if (modalFormData[item.FR_TableField] && item.FR_Rule.toLowerCase().includes("jm")) {
          modalFormData[item.FR_TableField] = ACrypto.setSS(modalFormData[item.FR_TableField]);
        }
      }
    }
    return modalFormData;
  }
  /**
   * @名字: 对字段值解密
   * @详情:仅适用于display类型的字段
   * @参数:
   * @返回值:
   */
  ReSetEncrypt() {
    const { modalFormData, ruleList } = this;
    for (let i = 0; i < ruleList.length; i++) {
      const item = ruleList[i];
      if (item.FR_RuleType === "display") {
        if (modalFormData[item.FR_TableField] && item.FR_Rule.toLowerCase().includes("jm")) {
          modalFormData[item.FR_TableField] = ACrypto.getSS(modalFormData[item.FR_TableField]);
        }
      }
    }
    return modalFormData;
  }
}

export default Ruler;
